
const MD5Util = require('./md5.js')
const Convert = require('./convert.js')

const pub_promptText = '请输入';

const timeSerch = 450;

var timerRun = false;

var enSerachWord = '';


var enonload = (action, callbackSetList) => {
    if (action.code === 'english') {
        document.onkeydown = (ev) => {
            if (ev.keyCode == 13)
                baiduApiGet(action, enSerachWord, callbackSetList)
        }
    }
}

var baidu = { appid: '', secret: '' };



window.exports = {
    "big": {
        mode: "list",  // 列表模式
        args: {
            // 进入插件时调用（可选）
            enter: (action, callbackSetList) => {

                enterFun(action, callbackSetList);
            },
            // 子输入框内容变化时被调用 可选 (未设置则无搜索)
            search: (action, searchWord, callbackSetList) => {
                let res = checkAppidSecret(callbackSetList);
                if (res)
                    serchFun(action, searchWord, callbackSetList);

            },
            // 用户选择列表中某个条目时被调用
            select: (action, itemData, callbackSetList) => {
                selectFun(action, itemData, callbackSetList);
            },
            // 子输入框为空时的占位符，默认为字符串"搜索"
            placeholder: pub_promptText
        }
    },
    "small": {
        mode: "list",  // 列表模式
        args: {
            // 进入插件时调用（可选）
            enter: (action, callbackSetList) => {
                enterFun(action, callbackSetList);
            },
            // 子输入框内容变化时被调用 可选 (未设置则无搜索)
            search: (action, searchWord, callbackSetList) => {
                let res = checkAppidSecret(callbackSetList);
                if (res)
                    serchFun(action, searchWord, callbackSetList);

            },
            // 用户选择列表中某个条目时被调用
            select: (action, itemData, callbackSetList) => {
                selectFun(action, itemData, callbackSetList);
            },
            // 子输入框为空时的占位符，默认为字符串"搜索"
            placeholder: pub_promptText
        }
    },
    "english": {
        mode: "list",  // 列表模式
        args: {
            // 进入插件时调用（可选）
            enter: (action, callbackSetList) => {
                enterEnFun(action, callbackSetList);
            },
            // 子输入框内容变化时被调用 可选 (未设置则无搜索)
            search: (action, searchWord, callbackSetList) => {
                enSerachWord = searchWord;
            },
            // 用户选择列表中某个条目时被调用
            select: (action, itemData, callbackSetList) => {
                selectFun(action, itemData, callbackSetList);
            },
            // 子输入框为空时的占位符，默认为字符串"搜索"
            placeholder: pub_promptText
        }
    },

    "appid": {
        mode: "list",
        args: {
            // 进入插件时调用（可选）
            enter: (action, callbackSetList) => {
            },
            // 子输入框内容变化时被调用 可选 (未设置则无搜索)
            search: (action, searchWord, callbackSetList) => {
                callbackSetList([{ title: searchWord, description: 'appid 信息' }]);
            },
            // 用户选择列表中某个条目时被调用
            select: (action, itemData, callbackSetList) => {
                utools.dbStorage.setItem('appid', itemData.title);
                window.utools.hideMainWindow();
                window.utools.outPlugin();
            },
            // 子输入框为空时的占位符，默认为字符串"搜索"
            placeholder: '请输入appid'
        }
    },
    "secret": {
        mode: "list",
        args: {
            // 进入插件时调用（可选）
            enter: (action, callbackSetList) => {
            },
            // 子输入框内容变化时被调用 可选 (未设置则无搜索)
            search: (action, searchWord, callbackSetList) => {
                callbackSetList([{ title: searchWord, description: 'secret key 信息' }]);
            },
            // 用户选择列表中某个条目时被调用
            select: (action, itemData, callbackSetList) => {
                utools.dbStorage.setItem('secretkey', itemData.title);
                window.utools.hideMainWindow();
                window.utools.outPlugin();
            },
            // 子输入框为空时的占位符，默认为字符串"搜索"
            placeholder: '请输入secretkey'
        }
    }
}

const selectFun = (action, itemData, callbackSetList) => {
    utools.copyText(itemData.title);
    utools.hideMainWindow();
    utools.setSubInputValue('');
    utools.outPlugin();
    // paste();
}


enterEnFun = (action, callbackSetList) => {
    enonload(action, callbackSetList);
    callbackSetList([]);
}

const enterFun = (action, callbackSetList) => {
    callbackSetList([]);
}

const serchFun = (action, searchWord, callbackSetList) => {
    if (searchWord === "") { callbackSetList([]); return; }
    if (searchWord !== '') {
        //如果定时器没运行, 则设置一个定时器, 指定延迟后执行, 执行完毕后清除定时器拦截
        if (timerRun === false) {
            timerRun = true;
            callbackSetList([]);
            setTimeout(function () {
                //请求百度接口
                let result = baiduApiGet(action, searchWord, callbackSetList);
                timerRun = false;
            }, timeSerch);
        }
    }
}


const baiduApiGet = (action, searchKey, callbackSetList) => {

    let appid = baidu.appid;
    let key = baidu.secret;
    let salt = (new Date).getTime();
    let query = searchKey;
    //多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
    let from = action.code != 'english' ? 'zh' : 'en';
    let to = action.code != 'english' ? 'en' : 'zh';
    let str1 = appid + query + salt + key;
    let sign = MD5Util.MD5(str1);

    let url = 'https://api.fanyi.baidu.com/api/trans/vip/translate?q=' + query + '&appid=' + appid + '&salt=' + salt + '&from=' + from + '&to=' + to + '&sign=' + sign;
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url, false);
    xhr.onreadystatechange = function () {
        // readyState == 4说明请求已完成
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                let data = JSON.parse(xhr.responseText);
                let errorCode = (data && data.error_code) || '';
                if (errorCode !== '') {
                    baiduError(errorCode, callbackSetList);
                    return;
                }
                let resutl = (data && data.trans_result) || [];

                let list = resutl.map(item => {
                    let value = ConvertText(action.code, item.dst);
                    return { title: value, description: item.src };
                })
                callbackSetList(list);

            } else {
                callbackSetList([{ title: '百度翻译接口响应错误' }]);
            }
        } else {
            callbackSetList([{ title: '出错了' }]);
        }
    }
    xhr.send();
}

const ConvertText = (code, value) => {
    if (code === 'big') return Convert.ToUpper(value);
    else if (code === 'small') return Convert.ToLowwer(value);
    else if (code === 'english') return value;
}

const baiduError = (errorCode, callbackSetList) => {
    let str = '';
    if (errorCode == 52001) str = '请求超时';
    else if (errorCode == 52002) str = '系统错误';
    else if (errorCode == 52003) str = '未授权用户';
    else if (errorCode == 54000) str = '必填参数为空';
    else if (errorCode == 54001) str = '签名错误';
    else if (errorCode == 54003) str = '访问频率受限';
    else if (errorCode == 54004) str = '账户余额不足';
    else if (errorCode == 54005) str = '长query请求频繁';
    else if (errorCode == 58000) str = '客户端IP非法';
    else if (errorCode == 58001) str = '译文语言方向不支持';
    else if (errorCode == 58002) str = '服务当前已关闭';
    else if (errorCode == 90107) str = '认证未通过或未生效';
    else str = '百度都没提供出来的错误 咋也不知道 咋也不敢问';
    callbackSetList([{ title: str, description: errorCode }]);
}




const checkAppidSecret = (callbackSetList) => {
    let appid = utools.dbStorage.getItem('appid');
    let secret = utools.dbStorage.getItem('secretkey');
    if (appid === null || appid === "" || appid === undefined) {
        callbackSetList([{ title: '请先设置百度 Appid' }]);
        return false;
    }
    if (secret === null || secret === "" || secret === undefined) {
        callbackSetList([{ title: '请先设置百度 Secret Key' }]);
        return false;
    }

    baidu.appid = appid;
    baidu.secret = secret;
    return true;
}



const paste = () => {
    if (utools.isWindows()) {
        utools.simulateKeyboardTap('v', 'ctrl')
    }
    if (utools.isMacOs()) {
        utools.simulateKeyboardTap('v', 'command')
    }
    if (utools.isLinux()) {
        utools.simulateKeyboardTap('v', 'ctrl')
    }
}




